package org.tgcloud.group.core.ExportUtils;

import cn.hutool.core.map.MapUtil;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: zhy
 * @create: 2023-08-21 11:00
 * @description: 图片导入工具类
 */
public class PictureUtil {

    /**
     * 获取excel表中的图片
     *
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     * @throws EncryptedDocumentException
     * @Param fis 文件输入流
     * @Param sheetNum Excel表中的sheet编号
     */
    public static Map<String, PictureData> getPictureFromExcel(File file, int sheetNum) throws EncryptedDocumentException, InvalidFormatException, IOException {

        //获取图片PictureData集合
        String fileName = file.getName();
        Workbook workbook = null;
        if (StringUtil.isEmpty(fileName)) {
            return null;
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        if (fileName.endsWith("xls")) {
            //2003
            workbook = new HSSFWorkbook(fileInputStream);
            HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(sheetNum - 1);
            Map<String, PictureData> pictures = getPictures(sheet);
            return pictures;
        } else if (fileName.endsWith("xlsx")) {
            //2007
            workbook = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(sheetNum - 1);
            Map<String, PictureData> pictures = getPictures(sheet);
            return pictures;
        }
        return new HashMap();
    }


    /**
     * 获取图片和位置 (xls版)
     * @param sheet
     * @return
     * @throws IOException
     */
    public static Map<String, PictureData> getPictures (HSSFSheet sheet) throws IOException {
        Map<String, PictureData> map = new HashMap<String, PictureData>();
        HSSFPatriarch patriarch = sheet.getDrawingPatriarch();
        if (null != patriarch){
            List<HSSFShape> list = patriarch.getChildren();
            for (HSSFShape shape : list) {
                if (shape instanceof HSSFPicture) {
                    HSSFPicture picture = (HSSFPicture) shape;
                    HSSFClientAnchor cAnchor = picture.getClientAnchor();
                    PictureData pdata = picture.getPictureData();
                    String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号
                    map.put(key, pdata);
                }
            }
        }
        return map;
    }

    /**
     * 获取图片和位置 (xlsx版)
     * @param sheet
     * @return
     * @throws IOException
     */
    public static Map<String, PictureData> getPictures (XSSFSheet sheet) throws IOException {
        Map<String, PictureData> map = new HashMap<String, PictureData>();
        List<POIXMLDocumentPart> list = sheet.getRelations();
        for (POIXMLDocumentPart part : list) {
            if (part instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) part;
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    XSSFPicture picture = (XSSFPicture) shape;
                    XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();
                    CTMarker marker = anchor.getFrom();
                    String key = marker.getRow() + "-" + marker.getCol();
                    XSSFPictureData pictureData = picture.getPictureData();
                    map.put(key, pictureData);
                }
            }
        }
        return map;
    }


    public static void main(String [] args) throws IOException {
        File file = new File("D:\\upload\\download\\file\\2025\\03\\03\\Media_202503031722104657595481.xlsx");
        //获取图片数据
        Map<String, PictureData> map = getPictureFromExcel(file, 1);
        //根据图片行列位置获取图片
        PictureData picData = (PictureData)map.get("1"+"-"+11);
        //后缀名
        String extension = picData.suggestFileExtension();
        byte[] data = picData.getData();
        String pic = org.tgcloud.group.core.StringUtil.generateOrderIdByName("pic");
        FileOutputStream out = new FileOutputStream("D:\\upload\\download\\file\\2025\\03\\03\\Media\\" + pic + "." + extension);
        out.write(data);
        out.close();
    }



//    public static String getPicturesUrl(File file, Integer sheetNum, Integer rowNum) throws IOException {
//        String path = "/home/checkorder/download_pic";
//        String name = file.getName();
//        String picName = name.substring(0, name.indexOf("."));
//        String pic = "pic_" + picName + "_" + rowNum;
//        String url = pic + ".png";
//        //获取图片数据
//        System.out.println("开始上传图片====》1===>" + System.currentTimeMillis());
//        doInputPic(sheetNum, path, url, file, rowNum);
//        return url;
//    }


//    private static void doInputPic(Integer sheetNum, String path, String url, File file, Integer rowNum){
//        System.out.println("异步线程 =====> 开始 =====> " + System.currentTimeMillis());
//        ExecutorService executorService = Executors.newFixedThreadPool(200);
//        executorService.submit(()->{
//            try{
//                System.out.println("异步线程 =====> 进行中 =====> " + System.currentTimeMillis());
//                Map<String, PictureData> map = getPictureFromExcel(file, sheetNum);
//                if (null == map || MapUtil.isEmpty(map)){
//                    return "";
//                }else {
//                    System.out.println("开始上传图片====》2===>" + System.currentTimeMillis());
//                    PictureData picData = (PictureData)map.get((rowNum)+"-"+7);
//                    if (null != picData){
//                        //后缀名
//                        String extension = picData.suggestFileExtension();
//                        byte[] data = picData.getData();
//                        System.out.println("开始上传图片====》3===>" + System.currentTimeMillis());
//                        FileOutputStream out = new FileOutputStream(path + "/" + url);
//                        BufferedOutputStream bos = new BufferedOutputStream(out);
//                        out.write(data);
//                        out.close();
//                        bos.close();
//                    }
//                }
//                executorService.shutdown(); // 回收线程池
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//
//        });
//        System.out.println("异步线程 =====> 结束 =====> " + System.currentTimeMillis());
//    }

    public static void uploadAndInstallImg(File insFile,File uploadFile){
        try {
            // 创建输入流 文件从磁盘输入到内存中；从文件系统中的文件获取输入字节。 什么文件可用取决于主机环境。
            InputStream fis = new FileInputStream(insFile);
            // 创建输出流 文件充内存输出到磁盘中 ；用于写入诸如图像数据的原始字节流。
            OutputStream fos = new FileOutputStream(uploadFile);

            byte[] buff = new byte[1024];    // 缓冲区  用来临时缓存文件
            int temp ;

            // (temp = fis.read(buff)) != -1   读入缓冲区的总字节数，如果没有更多的数据，因为文件的结尾已经到达， -1 。
            while ((temp = fis.read(buff)) != -1){
                fos.write(buff);    // 将 buff.length 字节从指定的字节数组写入此文件输出流。
                System.out.println(buff);
            }
            fis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 将file转换成fileItem
     * @param file
     * @param fieldName
     * @return
     */
    private static FileItem getMultipartFile(File file, String fieldName){
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    private static MultipartFile getMultipartFile(File file){
        FileItem fileItem = getMultipartFile(file,"templFileItem");
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }


}
